package com.itheima.edu.info.manager.dao;

import com.itheima.edu.info.manager.domain.Student;

import java.io.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.TreeSet;

public class OthersStudentDao01 implements BaseStudentDao {
    private static ArrayList<Student> list = new ArrayList<>();

    static {
        try {

            BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("studentServer\\stu.txt"), "UTF-8"));
            String line;
            while ((line = br.readLine()) != null) {
                String[] splitLine = line.split(",");
                Student stuTemp = new Student(splitLine[0], splitLine[1], splitLine[2], splitLine[3]);
                list.add(stuTemp);
            }
            br.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    //添加
    public boolean addStudenet(Student student) {
        boolean add = list.add(student);
        reSave();
        return add;
    }

    //查看学生
    public Student[] findAllStudent() {
        return list.toArray(new Student[list.size()]);
    }

    //删除学生
    public void deleteStudent(String id) {
        int index = getIndex(id);
        list.remove(index);
        reSave();
    }
    //修改学生
    public void updateStudent(Student student, String id) {
        int index = getIndex(id);
        list.set(index, student);
        reSave();
    }

    //获取指定学号在数组中的索引
    public int getIndex(String id) {
        int index = -1;
        for (int i = 0; i < list.size(); i++) {
            if (
                    list.get(i) != null && id.equals(list.get(i).getId())) {
                index = i;
            }
        }
        return index;
    }

   //将数据刷新到文件中
    private void reSave() {
        try {
            //输出流
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("studentServer\\stu.txt"), "UTF-8"));
            //将list进行排序
            Collections.sort(list, new Comparator<Student>() {
                @Override
                public int compare(Student o1, Student o2) {
                    int result = o1.getAge().compareTo(o2.getAge());
                    result = result == 0 ? o1.getId().compareTo(o2.getId()) : result;
                    return result;
                }
            });
            for (Student student : list) {
                bw.write(student.toString());
                bw.newLine();
                bw.flush();
            }
            bw.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
